package com.kadron.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.Discount;
import com.kadron.entity.DiscountItem;

@AutoCreate
@BypassInterceptors
@Name("discountItemDAO")
public class KDiscountItemDAO extends KDAO<DiscountItem> {

	private static final Log LOG = LogFactory.getLog(KDiscountItemDAO.class);
	
	@SuppressWarnings("unchecked")
	public List<Long> getDiscountItemIDs(long discountId) {
		EntityManager em = getEntityManager();
		return em.createQuery("SELECT a.item.id FROM DiscountItem a WHERE " +
				"a.discount.id = :a_id ")
		.setParameter("a_id", discountId)
		.getResultList();
	}
	
	public Discount getDiscount(long itemId, Date moment) {
		EntityManager em = getEntityManager();
		try {
			return (Discount) em.createQuery("SELECT e.discount FROM DiscountItem e INNER JOIN e.discount d WHERE d.active=TRUE AND e.item.id = :item_id AND d.validFrom <= :moment AND d.validTo >= :moment AND d.type = 1 ORDER BY e.id DESC")
				.setParameter("item_id", itemId)
				.setParameter("moment", moment)
				.setMaxResults(1)
				.getSingleResult();			
		} catch (NoResultException e) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("No discount found for itemId="+itemId);
			}
			return null;
		}
	}
	
	public void deleteItems(long discountId) {
		EntityManager em = getEntityManager();
		em.createQuery("DELETE FROM DiscountItem e WHERE " +
		"e.discount.id = :d_id ")
		.setParameter("d_id", discountId)
		.executeUpdate();
	}
	
	public void deleteItem(long discountId, long itemId) {
		EntityManager em = getEntityManager();
		em.createQuery("DELETE FROM DiscountItem e WHERE e.discount.id = :d_id AND e.item.id = :item_id")
			.setParameter("d_id", discountId)
			.setParameter("item_id", itemId)
			.executeUpdate();
	}
	
}
